/**  
 * @Title: UserServiceImpl.java
 * @Package org.wk.user.service
 * @Description: TODO【】
 * @author df.w 
 * @date 2018年5月3日 下午2:34:31
 * @version V1.0  
 */ 

package org.wk.user.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wk.account.service.SubAccountService;
import org.wk.common.enums.SmsCodeType;
import org.wk.common.service.SmsService;
import org.wk.core.common.tool.GeneratorStringUtils;
import org.wk.core.common.tool.HashUtils;
import org.wk.core.common.tool.RegexUtils;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.db.tool.WebUtils;
import org.wk.user.dao.UserDao;
import org.wk.user.domain.User;
import org.wk.user.enums.*;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.wk.user.view.TokenModel;

/**
 * @ClassName	: UserServiceImpl
 * @Package		：org.wk.user.service
 * @Author df.w 
 * @Create Time	：2018年5月3日 下午2:34:31
 * @Description	: 
 */
@Transactional
@Service
public class LoginServiceImpl implements LoginService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private LoginTokenService loginTokenService;
	
	@Autowired
	private SubAccountService subAccountService;
	@Autowired
	private UserPromoteRelationService userPromoteRelationService;
	
	/* (非 Javadoc)
	 * <p>Title: 用户注册</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#regist(com.alibaba.fastjson.JSONObject)
	 */

	@Override
	public ResponseVo regist(JSONObject jsonObject) {

		//判断用户是否有资格帮别人注册
		String userId = WebUtils.getUser().getId();
		Optional<User> userOpt = userDao.findById(userId);
		User users = userOpt.get();
		if(users.getIdentityCode()<1){
			return ResponseVo.error("用户没有资格注册");
		}


		// TODO Auto-generated method stub
		logger.info(jsonObject.toJSONString());
		//商家手机号码
		String mobileNumber = jsonObject.getString("mobile_number");
		//商家的推广码
		String promoCode = jsonObject.getString("mobile_number");
		//商家微信号
		String weChat = jsonObject.getString("weChat");
		//商家姓名
		String userName = jsonObject.getString("realName");
		//商家登录密码
		String password = jsonObject.getString("password");
		if (Strings.isNullOrEmpty(mobileNumber)||!RegexUtils.checkMobileNum(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
		}
		if (isMobileNumberExist(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_EXIST);
		}
		if (Strings.isNullOrEmpty(password)|| password.contains(" ") || password.length() < 6) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}

		User user = new User();
		user.setPromoCode(promoCode);
		user.setReferralCode(userId);
		user.setMobileNumber(mobileNumber);
		user.setWeChat(weChat);
		user.setUserName(userName);
		String salt = UUID.randomUUID().toString();
		user.setSalt(salt);
		user.setStatus(UserStatus.NORMAL.getCode());
		user.setIdentityName(IdentityType.AVERAGE.getName());
		user.setPassword(HashUtils.encodePwd(password,salt));
		user = userDao.save(user);

		//新增推广关系
		if (userId!=null){
			userPromoteRelationService.addRelationship(userId, user.getId());
			//subAccountService.promoteAccountHandler(userId);
		}

		//用户注册后账户变动
		//生成用户账户体系
		//subAccountService.checkAccountNum(user.getId());
		//subAccountService.registerAccountHandler(user.getId());
		return ResponseVo.success();
	}

	@Override
	public ResponseVo registTemp(JSONObject jsonObject) {
		logger.info(jsonObject.toJSONString());

		String mobileNumber = jsonObject.getString("mobile_number");
		if (Strings.isNullOrEmpty(mobileNumber)||!RegexUtils.checkMobileNum(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
		}
		if (isMobileNumberExist(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_EXIST);
		}
		String password = jsonObject.getString("password");
		if (Strings.isNullOrEmpty(password)|| password.contains(" ") || password.length() < 6) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}

		//推荐人编码
		String referralCode = jsonObject.getString("referral_code");

		String nickName = jsonObject.getString("nick_name");
		User user = new User();
		user.setNickName(nickName);
		user.setHeadSculpture("http://img.qiniu.vp359.com/default_headSculpture.png");
		user.setSexCode(SexType.SECRECY.getCode());
		user.setSexName(SexType.SECRECY.getName());
		user.setMobileNumber(mobileNumber);
		String salt = UUID.randomUUID().toString();
		user.setSalt(salt);
		user.setPassword(HashUtils.encodePwd(password,salt));
		//推广码为个人手机号
		user.setPromoCode(mobileNumber);
		//推荐人编码
		User referralUser = null;
		if (!Strings.isNullOrEmpty(referralCode)) {
			referralUser = userDao.findByPromoCode(referralCode);
			if (null == referralUser) {
				return new ResponseVo(ResponseCode.REFERRAL_CODE_INVALID);
			}
			user.setReferralCode(referralCode);
		}
		//未认证
		user.setIdcardStatusCode(IDCardStatus.UNVERIFIED.getCode());

		//用户身份设置
		String level = jsonObject.getString("level");
		if ("03".equals(level)) {
			user.setIdentityCode(IdentityType.AVERAGE.getCode());
			user.setIdentityName(IdentityType.AVERAGE.getName());
		}else {
			user.setIdentityCode(IdentityType.AVERAGE.getCode());
			user.setIdentityName(IdentityType.AVERAGE.getName());
		}

		user.setStatus(UserStatus.NORMAL.getCode());
		user = userDao.save(user);

		//新增推广关系
		if (referralUser!=null){
			userPromoteRelationService.addRelationship(referralUser.getId(), user.getId());
		}

		//用户注册后账户变动
		//生成用户账户体系
		subAccountService.checkAccountNum(user.getId());
		return ResponseVo.success().setData(user);
	}
	/**
	 * @Title		: isMobileNumberExist
	 * @Param		: @param mobileNumber
	 * @Param		: @return
	 * @Return Type 	：boolean true 存在  false 不存在
	 * @Description	: 校验手机号是否存在
	 */ 
	private boolean isMobileNumberExist(String mobileNumber) {
		User user = userDao.findByMobileNumber(mobileNumber);
		if (null==user) {
			return false;
		}
		return true;
	}


	
	/* (非 Javadoc)
	 * <p>Title: 用户登录</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#login(com.alibaba.fastjson.JSONObject)
	 */ 
	
	@Override
	public ResponseVo login(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		String mobileNumber = jsonObject.getString("mobile_number");
		String password = jsonObject.getString("password");
		
		if (Strings.isNullOrEmpty(mobileNumber)||Strings.isNullOrEmpty(password)) {
			return new ResponseVo(ResponseCode.ACCOUNTS_PASSWORD_ERROR);
		}


		User user = userDao.findByMobileNumber(mobileNumber);
		if (null == user) {
			return new ResponseVo(ResponseCode.ACCOUNTS_PASSWORD_ERROR);
		}
		if(UserStatus.FREEZE.getCode().equals(user.getStatus())) {
			return new ResponseVo(ResponseCode.ACCOUNTS_FREEZE);
		}

		String salt = user.getSalt();
		String tempPwd = HashUtils.encodePwd(password,salt);
		if (!tempPwd.equals(user.getPassword())) {
			return new ResponseVo(ResponseCode.ACCOUNTS_PASSWORD_ERROR);
		}

		String userId = user.getId();
		String promoCode = user.getPromoCode();
		String nickName = user.getNickName();
		String headSculpture = user.getHeadSculpture();
		
//		String token = loginTokenService.generatorToken(userId, nickName, headSculpture);
		TokenModel tokenModel = loginTokenService.createToken(userId);
		if (null==tokenModel || tokenModel.getToken()==null) {
			return new ResponseVo(ResponseCode.LOGIN_FAIL_RETRY);
		}

//		Map<String, String> userInfo = new HashMap<>();
//		userInfo.put("user_id", userId);
//		userInfo.put("nick_name", nickName);
//		userInfo.put("head_sculpture", headSculpture);
//		userInfo.put("mobile_number", user.getMobileNumber());
//		userInfo.put("sexCode", user.getSexCode());


		Map<String, Object> resData = new HashMap<>();
		resData.put("userId", userId);
		resData.put("token", tokenModel.getToken());
		resData.put("promoCode", promoCode);
//		resData.put("user", userInfo);
		subAccountService.loginAccountHandler(userId);
		return ResponseVo.success().setData(resData);
	}


	
	/* (非 Javadoc)
	 * <p>Title: resetPasswordBySmsCode</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.LoginService#resetPasswordBySmsCode(com.alibaba.fastjson.JSONObject)
	 */ 
	
	@Override
	public ResponseVo resetPasswordBySmsCode(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		String mobileNumber = jsonObject.getString("mobile_number");
		if (Strings.isNullOrEmpty(mobileNumber)||!RegexUtils.checkMobileNum(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
		}
		//判断该用户是否存在
		User user = userDao.findByMobileNumber(mobileNumber);
		if (null==user) {
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}
		String password = jsonObject.getString("password");
		if (Strings.isNullOrEmpty(password)|| password.contains(" ") || password.length() < 6) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}
		
		//校验手机验证码
		String smsCode = jsonObject.getString("sms_code");
		if (Strings.isNullOrEmpty(smsCode)) {
			return new ResponseVo(ResponseCode.SMS_CODE_EMPTY);
		}	
		if (!smsService.checkSmsCode(mobileNumber, smsCode, SmsCodeType.MODIFY_PASSWORD.getCode())) {
			return new ResponseVo(ResponseCode.SMS_CODE_ERROR);
		}
		String salt = UUID.randomUUID().toString();
		user.setSalt(salt);
		user.setPassword(HashUtils.encodePwd(password,salt));
		userDao.update(user);
		
		return ResponseVo.success();

	}

}
